package com.java110.mall.cart.bmo.housekeepingServPoolUser.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.mall.cart.bmo.housekeepingServPoolUser.ISaveHousekeepingServPoolUserBMO;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.account.AccountDto;
import com.java110.dto.distributionMode.DistributionModeDto;
import com.java110.dto.housekeeping.HousekeepingServPoolDto;
import com.java110.dto.housekeeping.HousekeepingServPoolUserDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.dto.storeOrder.StoreOrderCartEventDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.acct.IAccountInnerServiceSMO;
import com.java110.intf.cart.*;
import com.java110.intf.system.IFileInnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.account.AccountDetailPo;
import com.java110.po.housekeeping.HousekeepingServPoolPo;
import com.java110.po.housekeeping.HousekeepingServPoolUserPo;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.po.storeOrder.StoreOrderCartEventPo;
import com.java110.po.storeOrder.StoreOrderCartFeePo;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.lock.DistributedLock;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.DateUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service("saveHousekeepingServPoolUserBMOImpl")
public class SaveHousekeepingServPoolUserBMOImpl implements ISaveHousekeepingServPoolUserBMO {
    private static Logger logger = LoggerFactory.getLogger(SaveHousekeepingServPoolUserBMOImpl.class);

    @Autowired
    private IHousekeepingServPoolUserInnerServiceSMO housekeepingServPoolUserInnerServiceSMOImpl;


    @Autowired
    private IHousekeepingServPoolInnerServiceSMO housekeepingServPoolInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartEventInnerServiceSMO storeOrderCartEventInnerServiceSMOImpl;

    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartFeeInnerServiceSMO storeOrderCartFeeInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartSendInnerServiceSMO storeOrderCartSendInnerServiceSMOImpl;
    @Autowired
    private IAccountInnerServiceSMO accountInnerServiceSMOImpl;
    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;
    @Autowired
    private IHousekeepingServFeeInnerServiceSMO housekeepingServFeeInnerServiceSMOImpl;
    //派单
    public static final String ACTION_DISPATCH = "DISPATCH";

    //转单
    public static final String ACTION_TRANSFER = "TRANSFER";

    //退单
    public static final String ACTION_BACK = "BACK";

    //域
    public static final String DOMAIN_COMMON = "DOMAIN.COMMON";

    //键(维修师傅未处理最大单数)
    public static final String REPAIR_NUMBER = "REPAIR_NUMBER";

    /**
     * 添加小区信息
     *
     * @param housekeepingServPoolUserPo
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> save(HousekeepingServPoolUserPo housekeepingServPoolUserPo) {

        HousekeepingServPoolUserDto housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
        housekeepingServPoolUserDto.setShopId(housekeepingServPoolUserPo.getShopId());
        housekeepingServPoolUserDto.setPoolId(housekeepingServPoolUserPo.getPoolId());

        housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsersCount(housekeepingServPoolUserDto);

        housekeepingServPoolUserPo.setRuId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_ruId));
        int flag = housekeepingServPoolUserInnerServiceSMOImpl.saveHousekeepingServPoolUser(housekeepingServPoolUserPo);

        if (flag > 0) {
            return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
    }

    @Override
    @Java110Transactional
    public ResponseEntity<String> poolDispatch(JSONObject reqJson) {
        ResponseEntity<String> responseEntity = null;
        //HousekeepingServPoolUserPo housekeepingServPoolUserPo = BeanConvertUtil.covertBean(reqJson, HousekeepingServPoolUserPo.class);

        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "用户不存在");

        reqJson.put("userName", userDtos.get(0).getName());
        reqJson.put("Tel", userDtos.get(0).getTel());

        String action = reqJson.getString("action");
        switch (action) {
            case ACTION_DISPATCH:
                responseEntity = dispacthRepair(reqJson);
                break;
            case ACTION_TRANSFER:
                responseEntity = transferRepair(reqJson);
                break;
            case ACTION_BACK:
                responseEntity = backRepair(reqJson);
                break;
        }
        return responseEntity;
    }

    @Override
    @Java110Transactional
    public ResponseEntity<String> poolGrabbing(JSONObject reqJson) {
        ResponseEntity<String> responseEntity = null;
        //HousekeepingServPoolUserPo housekeepingServPoolUserPo = BeanConvertUtil.covertBean(reqJson, HousekeepingServPoolUserPo.class);

        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "用户不存在");

        reqJson.put("userName", userDtos.get(0).getUserName());
        reqJson.put("Tel", userDtos.get(0).getTel());

        responseEntity = grabbingRepair(reqJson);


        return responseEntity;
    }

    private ResponseEntity<String> grabbingRepair(JSONObject reqJson) {
        ResponseEntity<String> responseEntity = null;
        String requestId = DistributedLock.getLockUUID();
        String key = this.getClass().getSimpleName() + reqJson.getString("poolId");
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);
            //获取当前处理员工id
            String staffId = reqJson.getString("userId");
            HousekeepingServPoolUserDto housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
            housekeepingServPoolUserDto.setStaffId(staffId);
            housekeepingServPoolUserDto.setState("10001"); //处理中
            int i = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsersCount(housekeepingServPoolUserDto);
            //取出开关映射的值(维修师傅未处理最大单数)
            String repairNumber = MappingCache.getValue(DOMAIN_COMMON, REPAIR_NUMBER);
            if (i >= Integer.parseInt(repairNumber)) {
                throw new IllegalArgumentException("您有超过" + Integer.parseInt(repairNumber) + "条未处理的订单急需处理，请处理完成后再进行抢单！");

            }
            //获取报修id
            String poolId = reqJson.getString("poolId");
            HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
            housekeepingServPoolDto.setPoolId(poolId);
            List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);
            if (housekeepingServPoolDtos == null || housekeepingServPoolDtos.size() < 1) {
                responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "数据错误！");
                return responseEntity;
            } else {
                //获取状态
                String state = housekeepingServPoolDtos.get(0).getState();
                if (state.equals("1000")) {   //1000表示未派单
                    String userId = reqJson.getString("userId");
                    String userName = reqJson.getString("userName");

                    //处理人信息
                    HousekeepingServPoolUserPo housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
                    housekeepingServPoolUserPo.setRuId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_ruId));
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.add(Calendar.SECOND, 30);
                    housekeepingServPoolUserPo.setStartTime(DateUtil.getFormatTimeString(calendar.getTime(), DateUtil.DATE_FORMATE_STRING_A));
                    housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_DOING);
                    housekeepingServPoolUserPo.setPoolId(reqJson.getString("poolId"));
                    housekeepingServPoolUserPo.setStaffId(userId);
                    housekeepingServPoolUserPo.setStaffName(userName);

                    freshPreStaff(reqJson, housekeepingServPoolUserPo);

                    housekeepingServPoolUserPo.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_AUDIT_USER);
                    housekeepingServPoolUserPo.setContext("抢单成功");
                    housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
                    int flag = housekeepingServPoolUserInnerServiceSMOImpl.saveHousekeepingServPoolUser(housekeepingServPoolUserPo);
                    if (flag < 1) {
                        throw new IllegalArgumentException("保存失败");
                    }

                    //将订单状态改为上门
                    updateStoreOrderCart(housekeepingServPoolDtos.get(0), reqJson);

                    modifyBusinessServPoolDispatch(reqJson, HousekeepingServPoolDto.STATE_TAKING);
                    responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_OK, ResultVo.MSG_OK);
                } else if (state.equals("1100")) {   //1100表示接单
                    responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "该订单处于接单状态，无法进行派单！");
                } else {
                    responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "状态异常！");
                }
            }
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }
        return responseEntity;
    }

    public ResponseEntity<String> releaseRepair(JSONObject reqJson) {
        ResponseEntity<String> responseEntity = null;


        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "用户不存在");

        reqJson.put("userName", userDtos.get(0).getUserName());
        reqJson.put("Tel", userDtos.get(0).getTel());
        //获取订单抢单记录
        HousekeepingServPoolUserDto housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
        housekeepingServPoolUserDto.setState("10001"); //处理中
        housekeepingServPoolUserDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolUserDto.setShopId(reqJson.getString("shopId"));
        List<HousekeepingServPoolUserDto> housekeepingServPoolUserDtos = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsers(housekeepingServPoolUserDto);
        if (housekeepingServPoolUserDtos == null || housekeepingServPoolUserDtos.size() < 1) {
            throw new IllegalArgumentException("该订单没有被抢单，无法释放！");

        }
        int pos = housekeepingServPoolUserDtos.size() - 1;

        //获取订单池订单
        String poolId = reqJson.getString("poolId");
        HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
        housekeepingServPoolDto.setPoolId(poolId);
        List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);
        if (housekeepingServPoolDtos == null || housekeepingServPoolDtos.size() < 1) {
            responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "数据错误！");
            return responseEntity;
        } else {
            //获取状态
            String state = housekeepingServPoolDtos.get(pos).getState();
            String ruId = housekeepingServPoolUserDtos.get(pos).getRuId();
            String perStaffId = housekeepingServPoolUserDtos.get(pos).getStaffId();
            String perStaffName = housekeepingServPoolUserDtos.get(pos).getStaffName();
            if (state.equals("1100")) {   //1000表示已接单

                //处理人信息
                HousekeepingServPoolUserPo housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.SECOND, 30);
                housekeepingServPoolUserPo.setEndTime(DateUtil.getFormatTimeString(calendar.getTime(), DateUtil.DATE_FORMATE_STRING_A));
                housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_RELEASE);
                housekeepingServPoolUserPo.setRuId(ruId);
                int flag = housekeepingServPoolUserInnerServiceSMOImpl.updateHousekeepingServPoolUser(housekeepingServPoolUserPo);
                if (flag < 1) {
                    throw new IllegalArgumentException("保存失败");
                }

                String userId = reqJson.getString("userId");
                String userName = reqJson.getString("userName");

                //处理人信息
                housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
                housekeepingServPoolUserPo.setRuId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_ruId));
                calendar.setTime(new Date());
                calendar.add(Calendar.SECOND, 30);
                housekeepingServPoolUserPo.setStartTime(DateUtil.getFormatTimeString(calendar.getTime(), DateUtil.DATE_FORMATE_STRING_A));
                housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_CLOSE);
                housekeepingServPoolUserPo.setPoolId(reqJson.getString("poolId"));
                housekeepingServPoolUserPo.setStaffId(userId);
                housekeepingServPoolUserPo.setStaffName(userName);
                housekeepingServPoolUserPo.setPreStaffId(perStaffId);
                housekeepingServPoolUserPo.setPreStaffName(perStaffName);
                housekeepingServPoolUserPo.setPreRuId(ruId);
                housekeepingServPoolUserPo.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_AUDIT_USER);
                housekeepingServPoolUserPo.setContext("手工释放订单完成");
                housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
                flag = housekeepingServPoolUserInnerServiceSMOImpl.saveHousekeepingServPoolUser(housekeepingServPoolUserPo);
                if (flag < 1) {
                    throw new IllegalArgumentException("保存失败");
                }
                //将订单状态改为上门
                releaseStoreOrderCart(housekeepingServPoolDtos.get(0), reqJson);

                modifyBusinessServPoolDispatch(reqJson, HousekeepingServPoolDto.STATE_WAIT);
                responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_OK, ResultVo.MSG_OK);
            } else if (state.equals("1000")) {   //1100表示待处理
                responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "该订单处于待处理状态，无法进行释放！");
            } else {
                responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "状态异常！");
            }
        }

        return responseEntity;
    }

    private void myWithholdAccount(StoreOrderCartDto tmpStoreOrderCartDto, double amount) {
        UserDto userDto = new UserDto();
        userDto.setUserId(tmpStoreOrderCartDto.getPersonId());
        List<UserDto> userDtoList = userV1InnerServiceSMOImpl.queryUsers(userDto);
        if (userDtoList == null || userDtoList.size() < 1) {
            throw new IllegalArgumentException("用户信息查询失败，请检查用户状态");
        }
        UserDto userTel = new UserDto();
        userTel.setTel(userDtoList.get(0).getTel());
        List<UserDto> userDtoListTel = userV1InnerServiceSMOImpl.queryUsers(userTel);
        if (userDtoListTel == null || userDtoListTel.size() < 1) {
            throw new IllegalArgumentException("通过用户手机查询失败，请检查用户状态");
        }
        List<String> temObjId = new ArrayList<>();
        for (UserDto user : userDtoListTel) {
            temObjId.add(user.getUserId());
        }
        AccountDto accountDto = new AccountDto();
        accountDto.setObjIds(temObjId.toArray(new String[temObjId.size()]));
        accountDto.setObjType(AccountDto.OBJ_TYPE_PERSON);
        accountDto.setAcctType(AccountDto.ACCT_TYPE_TIME);
        if (DistributionModeDto.FEE_MODE_TYPE_M.equals(MappingCache.getValue(DistributionModeDto.DOMAIN_AMLL, DistributionModeDto.FEE_MODE_TYPE))) {
            accountDto.setObjType(AccountDto.OBJ_TYPE_STORE);
            accountDto.setAcctType(AccountDto.ACCT_TYPE_CASH);
        }
        List<AccountDto> accountDtoList = accountInnerServiceSMOImpl.queryAccounts(accountDto);
        if (accountDtoList == null || accountDtoList.size() < 1) {
            throw new IllegalArgumentException("账户信息查询失败，请检查账户状态");
        }

        AccountDetailPo accountDetailPo = new AccountDetailPo();
        accountDetailPo.setAcctId(accountDtoList.get(0).getAcctId());
        accountDetailPo.setObjId(accountDtoList.get(0).getObjId());
        accountDetailPo.setObjType(accountDtoList.get(0).getAcctType());
        accountDetailPo.setOrderId(tmpStoreOrderCartDto.getOrderId());
        accountDetailPo.setAmount(amount + "");
        int flag = accountInnerServiceSMOImpl.withholdAccount(accountDetailPo);
        if (flag < 1) {
            throw new IllegalArgumentException("扣款失败");
        }
    }

    /**
     * 保存待支付费用
     *
     * @param reqJson
     * @param fees
     */
    private double _doSaveNewFees(JSONObject reqJson, JSONArray fees) {
        BigDecimal outPayPrice = new BigDecimal(0);
        if (fees == null || fees.size() < 1) {
            return outPayPrice.doubleValue();
        }

        //根据poolId 查询 cartId
        HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
        housekeepingServPoolDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolDto.setShopId(reqJson.getString("shopId"));
        List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);
        String cartId = "";
        if (housekeepingServPoolDtos == null || housekeepingServPoolDtos.size() < 1) {
            cartId = GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_cartId);
        } else {
            cartId = housekeepingServPoolDtos.get(0).getCartId();
        }
        JSONObject fee = null;
        for (int feeIndex = 0; feeIndex < fees.size(); feeIndex++) {
            fee = fees.getJSONObject(feeIndex);
            if (!StringUtil.isEmpty(fee.getString("checked")) && "false".equals(fee.getString("checked"))) {
                continue;
            }
            StoreOrderCartFeePo storeOrderCartFeePo = new StoreOrderCartFeePo();
            storeOrderCartFeePo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));
            storeOrderCartFeePo.setCartId(cartId);
            storeOrderCartFeePo.setShopId(reqJson.getString("shopId"));
            storeOrderCartFeePo.setFeeConfigId(fee.getString("configId"));
            storeOrderCartFeePo.setFeeName(fee.getString("feeName"));
            storeOrderCartFeePo.setPrice(fee.getString("price"));
            storeOrderCartFeePo.setPayPrice(fee.getString("payPrice"));
            outPayPrice = outPayPrice.add(new BigDecimal(Double.parseDouble(fee.getString("payPrice")))).setScale(2, BigDecimal.ROUND_HALF_UP);

            storeOrderCartFeePo.setPayWay("-1");
            //1001 未支付、2002 已支付
            storeOrderCartFeePo.setState("1001");
            storeOrderCartFeePo.setExtOrderId("-1");
            storeOrderCartFeePo.setRemark("");
            storeOrderCartFeePo.setUpdateTime(DateUtil.getNow("yyyy-MM-dd HH:mm:ss"));
            int flag = storeOrderCartFeeInnerServiceSMOImpl.saveStoreOrderCartFee(storeOrderCartFeePo);
            if (flag < 1) {
                throw new IllegalArgumentException("订单费用失败");
            }
        }

        return outPayPrice.doubleValue();
    }


    private ResponseEntity<String> backRepair(JSONObject reqJson) {

        //查询订单状态
        HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
        housekeepingServPoolDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolDto.setShopId(reqJson.getString("shopId"));
        List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);
        Assert.listOnlyOne(housekeepingServPoolDtos, "当前用户没有需要处理订单或存在多条");


        String userId = reqJson.getString("userId");
        String userName = reqJson.getString("userName");

        HousekeepingServPoolUserDto housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
        housekeepingServPoolUserDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolUserDto.setShopId(reqJson.getString("shopId"));
        housekeepingServPoolUserDto.setState(HousekeepingServPoolUserDto.STATE_DOING);
        housekeepingServPoolUserDto.setStaffId(userId);
        List<HousekeepingServPoolUserDto> housekeepingServPoolUserDtos = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsers(housekeepingServPoolUserDto);
        Assert.listOnlyOne(housekeepingServPoolUserDtos, "当前用户没有需要处理订单");
        //把自己改成退单
        HousekeepingServPoolUserPo housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
        housekeepingServPoolUserPo.setRuId(housekeepingServPoolUserDtos.get(0).getRuId());
        housekeepingServPoolUserPo.setEndTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
        housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_BACK);
        housekeepingServPoolUserPo.setContext(reqJson.getString("context"));
        housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
        int flag = housekeepingServPoolUserInnerServiceSMOImpl.updateHousekeepingServPoolUser(housekeepingServPoolUserPo);
        if (flag < 1) {
            throw new IllegalArgumentException("把自己改成退单处理失败");
        }
        //处理人信息
        housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
        housekeepingServPoolUserPo.setRuId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_ruId));
        housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_DOING);
        housekeepingServPoolUserPo.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolUserPo.setStaffId(reqJson.getString("staffId"));
        housekeepingServPoolUserPo.setStaffName(reqJson.getString("staffName"));
        housekeepingServPoolUserPo.setStartTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
        housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
        housekeepingServPoolUserDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolUserDto.setStaffId(reqJson.getString("staffId"));
        housekeepingServPoolUserDto.setShopId(reqJson.getString("shopId"));
        housekeepingServPoolUserDto.setRuId(housekeepingServPoolUserDtos.get(0).getPreRuId());
        housekeepingServPoolUserDto.setStates(new String[]{HousekeepingServPoolUserDto.STATE_TRANSFER, HousekeepingServPoolUserDto.STATE_CLOSE});
        housekeepingServPoolUserDtos = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsers(housekeepingServPoolUserDto);

        if (housekeepingServPoolUserDtos == null || housekeepingServPoolUserDtos.size() < 1) {
            if (HousekeepingServPoolDto.REPAIR_WAY_GRABBING.equals(housekeepingServPoolDtos.get(0).getRepairWay())
                    || HousekeepingServPoolDto.REPAIR_WAY_TRAINING.equals(housekeepingServPoolDtos.get(0).getRepairWay())
            ) {
                modifyBusinessServPoolDispatch(reqJson, HousekeepingServPoolDto.STATE_WAIT);
                return ResultVo.success();
            } else {
                throw new IllegalArgumentException("非常抱歉当前不能退单");
            }
        }

        housekeepingServPoolUserPo.setPreStaffId(housekeepingServPoolUserDtos.get(0).getPreStaffId());
        housekeepingServPoolUserPo.setPreStaffName(housekeepingServPoolUserDtos.get(0).getPreStaffName());
        housekeepingServPoolUserPo.setPreRuId(housekeepingServPoolUserDtos.get(0).getPreRuId());
        housekeepingServPoolUserPo.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_AUDIT_USER);
        housekeepingServPoolUserPo.setContext("");
        housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
        if (housekeepingServPoolUserInnerServiceSMOImpl.saveHousekeepingServPoolUser(housekeepingServPoolUserPo) < 1) {
            throw new IllegalArgumentException("保存失败");
        }
        modifyBusinessServPoolDispatch(reqJson, HousekeepingServPoolDto.STATE_BACK);

        return ResultVo.success();
    }

    private void modifyBusinessServPoolDispatch(JSONObject reqJson, String state) {

        //查询报修单
        HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
        housekeepingServPoolDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolDto.setShopId(reqJson.getString("shopId"));
        List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);

        logger.debug("查询报修单结果：" + JSONObject.toJSONString(housekeepingServPoolDtos.get(0)));


        JSONObject businessPool = new JSONObject();
        businessPool.putAll(BeanConvertUtil.beanCovertMap(housekeepingServPoolDtos.get(0)));
        businessPool.put("state", state);
        //计算 应收金额
        HousekeepingServPoolPo housekeepingServPoolPo = BeanConvertUtil.covertBean(businessPool, HousekeepingServPoolPo.class);

        if (housekeepingServPoolInnerServiceSMOImpl.updateHousekeepingServPool(housekeepingServPoolPo) < 1) {
            throw new IllegalArgumentException("修改工单池状态失败");
        }

//        StoreOrderCartSendDto storeOrderCartSendDto = new StoreOrderCartSendDto();
//        storeOrderCartSendDto.setCartId( housekeepingServPoolDto.getCartId() );
//        storeOrderCartSendDto.setShopId( housekeepingServPoolDto.getShopId() );
//        List<StoreOrderCartSendDto> storeOrderCartSendDtos = storeOrderCartSendInnerServiceSMOImpl.queryStoreOrderCartSends( storeOrderCartSendDto );
//        if(storeOrderCartSendDtos != null && storeOrderCartSendDtos.size() > 0){
//            StoreOrderCartSendPo storeOrderCartSendPo = new StoreOrderCartSendPo();
//            storeOrderCartSendPo.setSendUserId( reqJson.getString("userId") );
//            storeOrderCartSendPo.setSendUserName( reqJson.getString("userName") );
//            storeOrderCartSendPo.setState( "1002" );
//            storeOrderCartSendPo.setSendUserTel( reqJson.getString("Tel") );
//            storeOrderCartSendPo.setSendTime( DateUtil.getNow( DateUtil.DATE_FORMATE_STRING_A ) );
//            storeOrderCartSendPo.setSendId( storeOrderCartSendDtos.get( 0 ).getSendId() );
//            int flag = storeOrderCartSendInnerServiceSMOImpl.updateStoreOrderCartSend( storeOrderCartSendPo );
//            if (flag < 1) {
//                throw new IllegalArgumentException( "修改派送状态失败" );
//            }
//        }
    }

    /**
     * 转单
     *
     * @param reqJson
     */
    private ResponseEntity<String> transferRepair(JSONObject reqJson) {
        String userId = reqJson.getString("userId");
        String userName = reqJson.getString("userName");

        HousekeepingServPoolUserDto housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
        housekeepingServPoolUserDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolUserDto.setShopId(reqJson.getString("shopId"));
        housekeepingServPoolUserDto.setState(HousekeepingServPoolUserDto.STATE_DOING);
        housekeepingServPoolUserDto.setStaffId(userId);
        List<HousekeepingServPoolUserDto> housekeepingServPoolUserDtos = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsers(housekeepingServPoolUserDto);
        Assert.listOnlyOne(housekeepingServPoolUserDtos, "当前用户没有需要处理订单");
        //插入派单者的信息
        HousekeepingServPoolUserPo housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
        housekeepingServPoolUserPo.setRuId(housekeepingServPoolUserDtos.get(0).getRuId());
        housekeepingServPoolUserPo.setEndTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
        housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_TRANSFER);
        housekeepingServPoolUserPo.setContext(reqJson.getString("context"));
        housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
        int flag = housekeepingServPoolUserInnerServiceSMOImpl.updateHousekeepingServPoolUser(housekeepingServPoolUserPo);
        if (flag < 1) {
            throw new IllegalArgumentException("修改失败");
        }
        //处理人信息
        housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
        housekeepingServPoolUserPo.setRuId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_ruId));
        housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_DOING);
        housekeepingServPoolUserPo.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolUserPo.setStaffId(reqJson.getString("staffId"));
        housekeepingServPoolUserPo.setStaffName(reqJson.getString("staffName"));
        housekeepingServPoolUserPo.setPreStaffId(userId);
        housekeepingServPoolUserPo.setStartTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
        housekeepingServPoolUserPo.setPreStaffName(userName);
        housekeepingServPoolUserPo.setPreRuId(housekeepingServPoolUserDtos.get(0).getRuId());
        housekeepingServPoolUserPo.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_AUDIT_USER);
        housekeepingServPoolUserPo.setContext("");
        housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));

        flag = housekeepingServPoolUserInnerServiceSMOImpl.saveHousekeepingServPoolUser(housekeepingServPoolUserPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存失败");
        }
        modifyBusinessServPoolDispatch(reqJson, HousekeepingServPoolDto.STATE_TRANSFER);

        ResponseEntity<String> responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_OK, ResultVo.MSG_OK);

        return responseEntity;
    }

    /**
     * 派单处理
     *
     * @param reqJson
     */
    private ResponseEntity<String> dispacthRepair(JSONObject reqJson) {
        //获取报修id
        ResponseEntity<String> responseEntity = null;
        String poolId = reqJson.getString("poolId");
        HousekeepingServPoolDto housekeepingServPoolDto = new HousekeepingServPoolDto();
        housekeepingServPoolDto.setPoolId(poolId);
        List<HousekeepingServPoolDto> housekeepingServPoolDtos = housekeepingServPoolInnerServiceSMOImpl.queryHousekeepingServPools(housekeepingServPoolDto);
        if (housekeepingServPoolDtos == null || housekeepingServPoolDtos.size() < 1) {
            responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "数据错误！");
            return responseEntity;
        } else {
            //获取状态
            String state = housekeepingServPoolDtos.get(0).getState();
            if (state.equals("1000")) {   //1000表示未派单
                String userId = reqJson.getString("userId");
                String userName = reqJson.getString("userName");
                String userTel = reqJson.getString("Tel");

                String ruId = GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_ruId);
                // 自己的单子状态修改为转单
                HousekeepingServPoolUserPo housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
                housekeepingServPoolUserPo.setRuId(ruId);
                housekeepingServPoolUserPo.setStartTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
                housekeepingServPoolUserPo.setEndTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A));
                housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_DISPATCH);
                housekeepingServPoolUserPo.setPoolId(reqJson.getString("poolId"));
                housekeepingServPoolUserPo.setStaffId(userId);
                housekeepingServPoolUserPo.setStaffName(userName);
                freshPreStaff(reqJson, housekeepingServPoolUserPo);
                housekeepingServPoolUserPo.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_AUDIT_USER);
                housekeepingServPoolUserPo.setContext(reqJson.getString("context"));
                housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
                int flag = housekeepingServPoolUserInnerServiceSMOImpl.saveHousekeepingServPoolUser(housekeepingServPoolUserPo);
                if (flag < 1) {
                    throw new IllegalArgumentException("保存失败");
                }
                //处理人信息
                housekeepingServPoolUserPo = new HousekeepingServPoolUserPo();
                housekeepingServPoolUserPo.setRuId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_ruId));
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.SECOND, 30);
                housekeepingServPoolUserPo.setStartTime(DateUtil.getFormatTimeString(calendar.getTime(), DateUtil.DATE_FORMATE_STRING_A));
                housekeepingServPoolUserPo.setState(HousekeepingServPoolUserDto.STATE_DOING);
                housekeepingServPoolUserPo.setPoolId(reqJson.getString("poolId"));
                housekeepingServPoolUserPo.setStaffId(reqJson.getString("staffId"));
                housekeepingServPoolUserPo.setStaffName(reqJson.getString("staffName"));
                housekeepingServPoolUserPo.setPreStaffId(userId);
                housekeepingServPoolUserPo.setPreStaffName(userName);
                housekeepingServPoolUserPo.setPreRuId(ruId);
                housekeepingServPoolUserPo.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_AUDIT_USER);
                housekeepingServPoolUserPo.setContext("");
                housekeepingServPoolUserPo.setShopId(reqJson.getString("shopId"));
                flag = housekeepingServPoolUserInnerServiceSMOImpl.saveHousekeepingServPoolUser(housekeepingServPoolUserPo);
                if (flag < 1) {
                    throw new IllegalArgumentException("保存失败");
                }
                //将订单状态改为上门
                updateStoreOrderCart(housekeepingServPoolDtos.get(0), reqJson);

                modifyBusinessServPoolDispatch(reqJson, HousekeepingServPoolDto.STATE_TAKING);
                responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_OK, ResultVo.MSG_OK);
            } else if (state.equals("1100")) {   //1100表示接单
                responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "该订单处于接单状态，无法进行派单！");
            } else {
                responseEntity = ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "状态异常！");
            }
        }

        return responseEntity;
    }

    private void updateStoreOrderCart(HousekeepingServPoolDto housekeepingServPoolDto, JSONObject reqJson) {

        if ("-1".equals(housekeepingServPoolDto.getCartId())) {
            return;
        }
        StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
        storeOrderCartDto.setCartId(housekeepingServPoolDto.getCartId());
        storeOrderCartDto.setShopId(housekeepingServPoolDto.getShopId());
        List<StoreOrderCartDto> storeOrderCartDtos = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCarts(storeOrderCartDto);

        Assert.listOnlyOne(storeOrderCartDtos, "购物车不存在");

        StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo();
        storeOrderCartPo.setCartId(housekeepingServPoolDto.getCartId());
        storeOrderCartPo.setShopId(housekeepingServPoolDto.getShopId());
        storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_SERV_DROP_IN);
        int flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
        if (flag < 0) {
            return;
        }

        StoreOrderCartEventPo storeOrderCartEventPo = new StoreOrderCartEventPo();
        storeOrderCartEventPo.setCartId(storeOrderCartPo.getCartId());
        storeOrderCartEventPo.setOrderId(storeOrderCartDtos.get(0).getOrderId());
        storeOrderCartEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
        storeOrderCartEventPo.setEventObjType("S");
        storeOrderCartEventPo.setEventObjId(housekeepingServPoolDto.getStaffId());
        storeOrderCartEventPo.setEventMsg("商家上门");
        storeOrderCartEventPo.setShopId(storeOrderCartPo.getShopId());
        storeOrderCartEventPo.setEventType(StoreOrderCartEventDto.EVENT_TYPE_COMMON);
        flag = storeOrderCartEventInnerServiceSMOImpl.saveStoreOrderCartEvent(storeOrderCartEventPo);

//        StoreOrderCartSendDto storeOrderCartSendDto = new StoreOrderCartSendDto();
//        storeOrderCartSendDto.setCartId( storeOrderCartPo.getCartId() );
//        storeOrderCartSendDto.setShopId( storeOrderCartPo.getShopId() );
//        List<StoreOrderCartSendDto> storeOrderCartSendDtos = storeOrderCartSendInnerServiceSMOImpl.queryStoreOrderCartSends( storeOrderCartSendDto );
//        if(storeOrderCartSendDtos != null && storeOrderCartSendDtos.size() > 0){
//            StoreOrderCartSendPo storeOrderCartSendPo = new StoreOrderCartSendPo();
//            storeOrderCartSendPo.setSendUserId( reqJson.getString("userId") );
//            storeOrderCartSendPo.setSendUserName( reqJson.getString("userName") );
//            storeOrderCartSendPo.setState( "1002" );
//            storeOrderCartSendPo.setSendUserTel( reqJson.getString("Tel") );
//            storeOrderCartSendPo.setSendTime( DateUtil.getNow( DateUtil.DATE_FORMATE_STRING_A ) );
//            storeOrderCartSendPo.setSendId( storeOrderCartSendDtos.get( 0 ).getSendId() );
//            flag = storeOrderCartSendInnerServiceSMOImpl.updateStoreOrderCartSend( storeOrderCartSendPo );
//            if (flag < 1) {
//                throw new IllegalArgumentException( "修改派送状态失败" );
//            }
//        }


        if (flag < 1) {
            throw new IllegalArgumentException("保存购物车事件失败");
        }

    }


    private void releaseStoreOrderCart(HousekeepingServPoolDto housekeepingServPoolDto, JSONObject reqJson) {

        if ("-1".equals(housekeepingServPoolDto.getCartId())) {
            return;
        }
        StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
        storeOrderCartDto.setCartId(housekeepingServPoolDto.getCartId());
        storeOrderCartDto.setShopId(housekeepingServPoolDto.getShopId());
        List<StoreOrderCartDto> storeOrderCartDtos = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCarts(storeOrderCartDto);

        Assert.listOnlyOne(storeOrderCartDtos, "购物车不存在");

        StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo();
        storeOrderCartPo.setCartId(housekeepingServPoolDto.getCartId());
        storeOrderCartPo.setShopId(housekeepingServPoolDto.getShopId());
        storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_SERV_R);
        int flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
        if (flag < 0) {
            return;
        }
//        StoreOrderCartSendDto storeOrderCartSendDto = new StoreOrderCartSendDto();
//        storeOrderCartSendDto.setCartId( storeOrderCartPo.getCartId() );
//        storeOrderCartSendDto.setShopId( storeOrderCartPo.getShopId() );
//        List<StoreOrderCartSendDto> storeOrderCartSendDtos = storeOrderCartSendInnerServiceSMOImpl.queryStoreOrderCartSends( storeOrderCartSendDto );
//        if(storeOrderCartSendDtos != null && storeOrderCartSendDtos.size() > 0){
//            StoreOrderCartSendPo storeOrderCartSendPo = new StoreOrderCartSendPo();
//            storeOrderCartSendPo.setSendUserId( reqJson.getString("userId") );
//            storeOrderCartSendPo.setSendUserName( reqJson.getString("userName") );
//            storeOrderCartSendPo.setState( "1004" );
//            storeOrderCartSendPo.setSendUserTel( reqJson.getString("Tel") );
//            storeOrderCartSendPo.setSendTime( DateUtil.getNow( DateUtil.DATE_FORMATE_STRING_A ) );
//            storeOrderCartSendPo.setSendId( storeOrderCartSendDtos.get( 0 ).getSendId() );
//            flag = storeOrderCartSendInnerServiceSMOImpl.updateStoreOrderCartSend( storeOrderCartSendPo );
//            if (flag < 1) {
//                throw new IllegalArgumentException( "修改派送状态失败" );
//            }
//        }

    }

    /**
     * 刷入上一处理人
     *
     * @param reqJson
     * @param housekeepingServPoolUserPo
     */
    private void freshPreStaff(JSONObject reqJson, HousekeepingServPoolUserPo housekeepingServPoolUserPo) {

        HousekeepingServPoolUserDto housekeepingServPoolUserDto = new HousekeepingServPoolUserDto();
        housekeepingServPoolUserDto.setPoolId(reqJson.getString("poolId"));
        housekeepingServPoolUserDto.setShopId(reqJson.getString("shopId"));
        //housekeepingServPoolUserDto.setPoolEvent(HousekeepingServPoolUserDto.POOL_EVENT_START_USER);
        List<HousekeepingServPoolUserDto> housekeepingServPoolUserDtos = housekeepingServPoolUserInnerServiceSMOImpl.queryHousekeepingServPoolUsers(housekeepingServPoolUserDto);
        if (housekeepingServPoolUserDtos == null || housekeepingServPoolUserDtos.size() < 1) {
            housekeepingServPoolUserPo.setPreStaffId("-1");
            housekeepingServPoolUserPo.setPreStaffName("-1");
            housekeepingServPoolUserPo.setPreRuId("-1");
        } else {
            int pos = housekeepingServPoolUserDtos.size() - 1;
            housekeepingServPoolUserPo.setPreStaffId(housekeepingServPoolUserDtos.get(pos).getStaffId());
            housekeepingServPoolUserPo.setPreStaffName(housekeepingServPoolUserDtos.get(pos).getStaffName());
            housekeepingServPoolUserPo.setPreRuId(housekeepingServPoolUserDtos.get(pos).getRuId());
        }
    }

}
